package com.jack.helloworld.util;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.ResolveInfo;

import com.orhanobut.logger.Logger;

import java.util.List;

/**
 * Created by Administrator on 2017/6/15.
 */
public class FuncUtil {

    public static Intent startAppByPackageName(Context context, String packageName) {
        Intent intent = null;
        PackageInfo pi = null;
        boolean flag = true;
        try {
            pi = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (Exception e) {
            flag = false;
            Logger.e(e, "FuncUtil#startAppByPackageName#ERR: " + e.getMessage());
        }

        if (flag) {
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            resolveIntent.setPackage(pi.packageName);

            List<ResolveInfo> apps = context.getPackageManager()
                    .queryIntentActivities(resolveIntent, 0);
            if (apps != null && apps.size() > 0) {
                ResolveInfo ri = apps.iterator().next();
                if (ri != null) {
                    String pkgName = ri.activityInfo.packageName;
                    String className = ri.activityInfo.name;

                    intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);

                    ComponentName cn = new ComponentName(pkgName, className);

                    intent.setComponent(cn);
                }
            }
        }
        return intent;

    }
}
